﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebEFDemo
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindStudnet();
            }
        }
        /// <summary>
        /// EF绑定数据源
        /// </summary>
        private void BindStudnet()
        {
            //using (EFDemoUserListEntities db = new EFDemoUserListEntities())
            //{
            //    DbSet<Student> list = db.Set<Student>();
            //    var stu = from s in db.Student
            //              join c in db.Class on s.classid equals c.classid
            //              select new { s.stuid, s.stuname, s.stuage, s.phone, s.email, c.classname };
            //    repert_EFDemo.DataSource = stu.ToList();
            //    repert_EFDemo.DataBind();
            //}
            using (EFDemoUserListEntities db = new EFDemoUserListEntities())
            {
                //实例化数据库访问上下文
                List<Student> list = db.Student.Where(s => true).ToList();
                List<StudentModel> listmodel = new List<StudentModel>();
                list.ForEach(s =>
                {
                    var model = new StudentModel()
                    {
                        //查询实体属性
                        stuid = s.stuid,
                        stuname = s.stuname,
                        stuage = s.stuage,
                        phone = s.phone,
                        email = s.email,
                        classid = Convert.ToInt32(s.classid),
                        classname = s.Class.classname
                    };
                    listmodel.Add(model);
                });
                repert_EFDemo.DataSource = listmodel;
                repert_EFDemo.DataBind();
            }
        }

        //repeater删除和修改
        protected void repert_EFDemo_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument);
            if (e.CommandName == "update")
            {
                Session["stuid"] = id;
                Server.Transfer("Update.aspx");
            }
            if (e.CommandName == "del")
            {
                Student stu = new Student();
                stu.stuid = id;
                EFDemoUserListEntities db = new EFDemoUserListEntities();
                db.Student.Attach(stu);
                db.Student.Remove(stu);
                int i = db.SaveChanges();
                Response.Write("<script>alert('删除成功！')</script>");
                BindStudnet();
            }
        }

        //添加成员的跳转
        protected void bnt_add_Click(object sender, EventArgs e)
        {
            Response.Redirect("Add.aspx");
        }
    }
}